//
//  WYJUserAccountViewModel.swift
//  MySinaWeibo
//
//  Created by eastriver on 16/10/8.
//  Copyright © 2016年 believewilliam. All rights reserved.
//

import UIKit
    private let filePath = ((NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last)! as NSString).appendingPathComponent("account.plist")

class WYJUserAccountViewModel: NSObject {
    // 定义一个单例对象
    static let sharedAccountViewModel: WYJUserAccountViewModel = WYJUserAccountViewModel()
    // 模型属性
    var userAccount: WYJUserAccount?
    var userLogin: Bool {
        if userAccount?.access_token != nil && userAccount?.isExpires == false {
            return true
        }
        // 默认是false
        return false
    }
    var iconURL: URL?
    
    override init() {
        super.init()
        self.userAccount = self.loadUserAccount()
        self.iconURL = URL(string: self.userAccount?.avatar_large ?? "")
    }
    
    internal func loadAccessToken(code: String, finished: @escaping (Bool) -> ()) {
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let parameters = ["client_id": client_id, "client_secret": client_secret, "grant_type": "authorization_code", "code": code, "redirect_uri": redirect_uri]
        WYJNetworkTool.sharedTool.request(method: .POST, urlString: urlString, parameters: parameters) { (responseObject, error) in
            if error != nil {
                finished(false)
                return
            }
            //            print(responseObject)
            // 获取用户信息
            self.loadUserInfo(dict: responseObject as! [String : Any], finished: finished)
            
        }
    }
    private func loadUserInfo(dict: [String: Any], finished: @escaping (Bool) -> ()) {
        let urlString = "https://api.weibo.com/2/users/show.json"
        let access_token = dict["access_token"]!
        let uid = dict["uid"]!
        let parameters = ["access_token": access_token, "uid": uid]
        WYJNetworkTool.sharedTool.request(method: .GET, urlString: urlString, parameters: parameters) { (responseObject, error) in
            if error != nil {
                return
            }
            //            print(responseObject)
            // 字典转模型，将用户信息保存到要地
            var userInfoDict = responseObject as! [String: Any]
            // 合并字典
            for keyValues in dict {
                userInfoDict[keyValues.key] = keyValues.value
            }
            let userAccount = WYJUserAccount(dict: userInfoDict)
            self.userAccount = userAccount
            //            print(userAccout)
            // 把用户信息保存到本地
            self.saveUserAccount(userAccount: userAccount)
            finished(true)
        }
    }
    private func saveUserAccount(userAccount: WYJUserAccount) {
//        // 获取沙盒中Documents文件夹路径
//        let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last
//        // 拼接文件存放路径
//        let filePath = (path! as NSString).appendingPathComponent("account.plist")
        NSKeyedArchiver.archiveRootObject(userAccount, toFile: filePath)
        print(filePath)
        
    }
    private func loadUserAccount() -> WYJUserAccount? {
        let userAccount = NSKeyedUnarchiver.unarchiveObject(withFile: filePath) as? WYJUserAccount
        return userAccount
    }

}
